<template>
    <el-dialog v-model="state.changePasswordDialog" title="修改密码" width="400px">
        <el-form class="login-form" :label-position="'top'" :rules="rules">
            <el-form-item label="输入原密码:" prop="oldPassword">
                <el-input v-model="passwordData.oldPassword" placeholder="请输入原密码" show-password></el-input>
            </el-form-item>
            <el-form-item label="请输入新密码:" prop="newPassword">
                <el-input v-model="passwordData.newPassword" placeholder="请输入新密码" show-password></el-input>
            </el-form-item>
        </el-form>
        <!-- 底部内容 -->
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="state.changePasswordDialog = false">取消</el-button>
                <el-button type="primary" @click="changeUserPassword">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
    import { reactive, ref, defineExpose } from 'vue'
    import { changePassword } from '@/api/userinfo.js'
    import { ElMessage } from 'element-plus'
    import { useRouter } from 'vue-router'
    const router = useRouter()
    //表单对象接口
    interface passwordData {
        oldPassword: string;
        newPassword: string;
    }
    //表单对象
    const passwordData = reactive({
        oldPassword: '',
        newPassword: ''
    })
    // 控制弹窗默认关闭
    const state = reactive({
        changePasswordDialog: false
    })
    // 打开弹窗
    const open = () => {
        state.changePasswordDialog = true
    }

    //修改密码 id newPassword oldPassword
    const changeUserPassword = async () => {
        const id = sessionStorage.getItem('id')
        if (passwordData.oldPassword && passwordData.newPassword) {
            const res = await changePassword(id as string, passwordData.newPassword, passwordData.oldPassword)
            console.log(res)
            if (res.status == 0) {
                ElMessage({
                    message: '修改成功！',
                    type: 'success',
                })
                state.changePasswordDialog = false
                router.replace('/login')
            } else {
                ElMessage.error('修改密码失败，请重新输入！')
            }
        } else {
            ElMessage.error('修改失败，请检查密码格式是否正确！')
        }
    }

    const rules = reactive({
        oldPassword: [
            { required: true, message: '请输入原密码', trigger: 'change' }
        ],
        newPassword: [
            { required: true, message: '6-12位密码,包含大小写字母,数字', trigger: 'change' }
        ]
    })
    defineExpose({
        open
    })
</script>
<style scoped lang="scss"></style>